/* TITLE BikiROM MegaBoard Bootloader Encryptor v0.1 */
/* Author: Chris Collins */
/* Last Modified: 31/08/2005 */

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <io.h>

#define Page 0x1EF
#define PageBlock 128
#define ByteBlock 256

int main(void)
{
	unsigned char CypherBlock[13];
	int Vector;
	char InputFirmware[40];	// For user to enter File name
	FILE  *infilep;	// Pointer to file
	FILE  *outfilep;

//        int i;
	char Pause;
	unsigned char Initial_Vector;
	unsigned char Incoming_Byte;
	unsigned char Encrypted_Byte;
	int Exit;


	/* Welcome Screen */
	printf("\n TITLE BikiROM MegaBoard Bootloader Decryptor v0.1\n");

	CypherBlock[0] = (unsigned char)25;
	CypherBlock[1] = (unsigned char)38;
	CypherBlock[2] = (unsigned char)133;
	CypherBlock[3] = (unsigned char)73;
	CypherBlock[4] = (unsigned char)17;
	CypherBlock[5] = (unsigned char)190;
	CypherBlock[6] = (unsigned char)107;
	CypherBlock[7] = (unsigned char)60;
	CypherBlock[8] = (unsigned char)194;
	CypherBlock[9] = (unsigned char)38;
	CypherBlock[10] = (unsigned char)191;
	CypherBlock[11] = (unsigned char)156;
	CypherBlock[12] = (unsigned char)6;

//	randomize();

//	printf(" Initial Vector: %d\n", Initial_Vector);

/*	for(i=0;i<13;i++)
	{
	CypherBlock[i] = (unsigned char)(rand() % 256);
     //	printf("%d , ", CypherBlock[i]);
	}*/


	do {
		printf("\n Enter encrypted firmware filename: ");
		fgets(InputFirmware, sizeof InputFirmware, stdin);  // Reads filename from keyboard

		InputFirmware[strlen(InputFirmware) - 1] = '\0';  // Repairs carriage return problem

		infilep = fopen(InputFirmware, "rb");  // open file as read for input

		if (infilep == NULL)  // if NULL, file has not been opened
		printf("\n ** ERROR: Cannot open %s for input\n", InputFirmware);
	} while (infilep == NULL);	// repeat this until user gets file right

	printf("\n Successfully opened file... processing... \n");


	outfilep = fopen("firmware.dec", "wb");

	fread(&Initial_Vector, sizeof (unsigned char), 1, infilep);
	printf(" Initial Vector: %d\n", Initial_Vector);

	Vector = (int)Initial_Vector;

	do
	{
		Exit = fread(&Incoming_Byte, sizeof (unsigned char), 1, infilep);

//		printf("%d, %d\n", Exit, (int)Incoming_Byte);

		Encrypted_Byte = Incoming_Byte ^ (unsigned char)CypherBlock[Vector];

		if (Exit == 1) fwrite(&Encrypted_Byte, sizeof (unsigned char), 1, outfilep);


		fread(&Incoming_Byte, sizeof (unsigned char), 1, infilep);
		fread(&Incoming_Byte, sizeof (unsigned char), 1, infilep);

		Vector++;
		if (Vector > 12) Vector = 0;
	}
	while (Exit == 1);



	fclose(outfilep);
	fclose(infilep);	// close files

	printf("\n Decryption complete. Output in firmware.dec\n");


//	printf("\n Paused. ");
//	scanf("%c", Pause);  // Reads filename from keyboard

	return 0;
}
